package com.starlink.common.log;

import com.starlink.common.log.dto.UserInfo;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * @author: lichao
 * @date: 2021-06-22 15:48:08
 */
public class DefaultUserInfoFunction implements UserInfoFunction{
    @Override
    public void save(HttpServletRequest request) {
        if (request.getHeader("X-User-Id") != null && !request.getHeader("X-User-Id").trim().equals("")) {
            UserInfo user = new UserInfo();
            user.setId(Long.valueOf(request.getHeader("X-User-Id")));

            final String headerUserName = request.getHeader("X-User-Name");
            if(Objects.nonNull(headerUserName)){
                try {
                    user.setName(URLDecoder.decode(headerUserName, "UTF-8").replace("\"", ""));
                } catch (UnsupportedEncodingException var8) {
                    user.setName(headerUserName);
                }
            }

            DefaultApplicationLogContext.USER_INFO_THREAD_LOCAL.set(user);
        }

    }
}
